package com.yuyou.fn.common.util;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * Created by wens on 16-9-23.
 */
public class Threads {

    private static ExecutorService executorService = Executors.newCachedThreadPool(makeThreadName("default-executor-thread"));

    private static ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(makeThreadName("default-scheduled-thread"));

    public static ThreadFactory makeThreadName(final String name) {
        return new ThreadFactory() {
            private AtomicLong count = new AtomicLong(0);

            @Override
            public Thread newThread(Runnable r) {
                return new Thread(r, String.format("%s-%d", name, count.incrementAndGet()));
            }
        };
    }

    public static Future<?> dispatch(Runnable runnable) {
        return executorService.submit(runnable);
    }

    public static void delay(final Runnable runnable, long delaySecond) {
        scheduledExecutorService.schedule(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                runnable.run();
                return null;
            }
        }, delaySecond, TimeUnit.SECONDS);
    }

}
